<?php

class Model_Sports
{
    private function prepareConnection(){
        if (!isset($this->db)){
            $db = Zend_Registry::get("db_main");
            if (!$db->connected) $db->connect();
            $this->db = $db->escoreboar;
        }
    }

    public function get($idSport){
        $this->prepareConnection();
        $sport = $this->db->sport->findOne( array('_id' =>$idSport) );
        return $sport;
    }

    private function changeKey($item, $newKey, $oldKey){
        $item[$newKey]=$item[$oldKey];
        unset($item[$oldKey]);
        return $item;
    }

    public function find(){
        $this->prepareConnection();
        $sports = $this->db->sport->find();
        $i=1;
        while($sports->hasNext()){
            $key="sport_".$i;
            $rt[$key]=$sports->getNext();

            $rt[$key]=$this->changeKey($rt[$key], "actions","as");

            foreach ($rt[$key]["actions"] as $k=>$action){
                $keyAction="action_".$k;
                $rt[$key]["actions"]=$this->changeKey($rt[$key]["actions"], $keyAction,$k);
                $rt[$key]["actions"][$keyAction]=$this->changeKey($rt[$key]["actions"][$keyAction], "name","n");
                $rt[$key]["actions"][$keyAction]=$this->changeKey($rt[$key]["actions"][$keyAction], "type","t");
                $rt[$key]["actions"][$keyAction]=$this->changeKey($rt[$key]["actions"][$keyAction], "value","v");
            }

            $rt[$key]=$this->changeKey($rt[$key], "parts","ps");
            foreach ($rt[$key]["parts"] as $k=>$parts){
                $keyPart="part_".$k;
                $rt[$key]["parts"]=$this->changeKey($rt[$key]["parts"], $keyPart,$k);
                $rt[$key]["parts"][$keyPart]=$this->changeKey($rt[$key]["parts"][$keyPart], "sequence","s");
                $rt[$key]["parts"][$keyPart]=$this->changeKey($rt[$key]["parts"][$keyPart], "duration","d");

            }

            $i++;
        }
        return $rt;
    }
}

